<template>
	<div class="article">
		<div class="title_btn">
			<input v-model="formData.title" class="title_input" placeholder="请输入标题" />
			<el-button type="primary" @click="open = true">保 存</el-button>
		</div>
		<v-md-editor
			v-model="formData.content"
			height="100%"
			placeholder="文章内容"
			:left-toolbar="leftToolbar"
			right-toolbar="toc preview"
			:disabled-menus="[]"
			@upload-image="handleUploadImage"
		></v-md-editor>

		<!-- 发布设置 -->
		<el-dialog v-model="open" title="保存文章" width="600" top="10vh" draggable>
			<el-form ref="formRef" :model="formData" :rules="rules" label-width="90px">
				<el-form-item label="文章标题" prop="title">
					<el-input v-model="formData.title" placeholder="请输入文章标题" />
				</el-form-item>
				<el-form-item label="文章摘要" prop="digest">
					<el-input
						v-model="formData.digest"
						type="textarea"
						rows="6"
						maxlength="300"
						show-word-limit
						placeholder="请输入文章摘要"
					/>
				</el-form-item>
				<el-form-item label="封面" prop="cover">
					<el-upload
						accept="image/jpeg, image/png"
						class="avatar-uploader"
						name="picture"
						:action="address + '/upload/picture'"
						:headers="{ Authorization: token }"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
					>
						<img v-if="formData.cover" :src="formData.cover" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="formData.status">
						<el-radio label="1">发布</el-radio>
						<el-radio label="0">仅保存</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="open = false">取 消</el-button>
				<el-button type="primary" @click="submit">确 认</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="Content">
import { ref, onActivated, onDeactivated } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { useLoginStore } from '@/store/login/login'
import { ResultEnum } from '@/global/constant'
import { uploadPicture } from '@/service/system/general'
import { insertArticle, selectArticleDetail, updateArticle } from '@/service/article/content'

const formData = ref<any>({ cover: '', status: '1', content: '' })
const route = useRoute()
onActivated(async () => {
	const { infoId } = route.params
	if (infoId) {
		const article = await selectArticleDetail({ infoId })
		formData.value = { ...article }
	}
})
onDeactivated(() => {
	formData.value = { cover: '', status: '1', content: '' }
})

const open = ref(false)
const rules = {
	title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
	digest: [{ required: true, message: '请输入文章摘要', trigger: 'blur' }]
}
const address = import.meta.env.VITE_PROXY_URL
const loginStore = useLoginStore()
const token = loginStore.token

const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
	if (response.code == ResultEnum.SUCCESS) {
		formData.value.cover = response.data[0].url
	}
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
	if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
		ElMessage.error('格式错误!')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('图片不能大于 2MB!')
		return false
	}
	return true
}

const leftToolbar = 'undo redo | h bold italic strikethrough hr ul ol quote table image code'

async function handleUploadImage(event: any, insertImage: any, files: any) {
	const formdata = new FormData()
	formdata.append('picture', files[0])
	const result = await uploadPicture(formdata)

	if (result.length) {
		for (const item of result) {
			insertImage({
				url: item.url,
				desc: item.filename
				// width: '800px'
				// height: 'auto',
			})
		}
	}
}

const formRef = ref()
function submit() {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			if (formData.value.id) {
				await updateArticle(formData.value)
				open.value = false
				ElMessage.success('已修改')
			} else {
				await insertArticle(formData.value)
				open.value = false
				ElMessage.success('文章已创建')
				formData.value = { cover: '', status: '1', content: '' }
			}
		}
	})
}
</script>

<style lang="less" scoped>
.article {
	height: calc(100% - 55px);
}
.title_btn {
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 40px;
	margin-bottom: 15px;
	background: #fff;
	padding: 0 15px;
	.title_input {
		width: 100%;
		height: 80%;
		font-size: 20px;
		border: none;
		outline: none;
	}
}
</style>
